const crypto = require('crypto');

export class Aes {
  static decrypt(appId, sessionKey, encryptedData, iv) {
    // base64 decode
    const sessionKeyBuffer = Buffer.from(sessionKey, 'base64');
    const encryptedDataBuffer = Buffer.from(encryptedData, 'base64');
    const ivBuffer = Buffer.from(iv, 'base64');

    try {
      // 解密
      const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKeyBuffer, ivBuffer);
      // 设置自动 padding 为 true，删除填充补位
      decipher.setAutoPadding(true);
      let decoded = decipher.update(encryptedDataBuffer, 'binary', 'utf8');
      decoded += decipher.final('utf8');

      decoded = JSON.parse(decoded);

      if (decoded.watermark.appid !== appId) {
        // throw new Error('Illegal Buffer');
        return null;
      }

      return decoded;
    } catch (err) {
      // throw new Error('Illegal Buffer');
      return null;
    }
  }
}